package com.axcbd.demo.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class HlsVideoBackupService {

    private String videoStreamUrl = "http://localhost:5000/video_feed"; // 替换为你的 Python 服务 IP
    private String backupDirectory = "video_backups"; // 备份文件存放目录
    private Map<String, String> backupTasks = new HashMap<>(); // 存储备份任务信息
    private boolean isBackupRunning = false; // 标记备份是否正在运行
    private Process ffmpegProcess = null; // 用于管理 FFmpeg 进程

    public void startBackup() {
        if (isBackupRunning) {
            System.out.println("备份任务已在运行！");
            return;
        }

        isBackupRunning = true;
        System.out.println("开始备份视频流为 HLS 格式...");

        new Thread(() -> {
            try {
                // 创建备份目录
                File dir = new File(backupDirectory);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 获取当前时间格式化后的字符串，用于备份文件命名
                LocalDateTime startBackupTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                String backupFolder = backupDirectory + "/backup_" + startBackupTime.format(formatter);
                Files.createDirectories(Paths.get(backupFolder));

                // FFmpeg 命令用于将视频流转换为 HLS 格式
                String ffmpegCommand = "D:/ffmpeg-7.1.1-essentials_build/bin/ffmpeg -i " + videoStreamUrl + " -c:v libx264 -c:a aac -hls_time 10 -hls_list_size 0 -hls_segment_filename " + backupFolder + "/segment_%03d.ts " + backupFolder + "/playlist.m3u8";

                // 启动 FFmpeg 进程
                ffmpegProcess = Runtime.getRuntime().exec(ffmpegCommand);

                // 检查 FFmpeg 进程是否正确启动
                if (ffmpegProcess == null) {
                    throw new IOException("FFmpeg process failed to start.");
                }

                // 记录备份任务的开始时间和文件路径
                backupTasks.put("startTime", startBackupTime.format(formatter));
                backupTasks.put("backupFolder", backupFolder);

                // 读取 FFmpeg 的错误输出
                InputStream errorStream = ffmpegProcess.getErrorStream();
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
                String line;
                while ((line = errorReader.readLine()) != null) {
                    System.err.println("FFmpeg Error: " + line);
                }

                // 等待 FFmpeg 进程完成（最长24小时）
                long startTime = System.currentTimeMillis();
                ffmpegProcess.waitFor(24, TimeUnit.HOURS); // 设置最长运行时间为24小时

                // 停止 FFmpeg 进程
                if (ffmpegProcess != null && ffmpegProcess.isAlive()) {
                    ffmpegProcess.destroy();
                }

                // 更新备份任务状态
                LocalDateTime endBackupTime = LocalDateTime.now();
                backupTasks.put("endTime", endBackupTime.format(formatter));
                backupTasks.put("status", "completed");

                System.out.println("视频流备份完成，备份文件夹：" + backupFolder);

            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                backupTasks.put("status", "failed");
                isBackupRunning = false;
            } finally {
                // 确保 FFmpeg 进程被销毁
                if (ffmpegProcess != null && ffmpegProcess.isAlive()) {
                    ffmpegProcess.destroy();
                }
            }
        }).start();
    }

    public Map<String, String> getBackupTasks() {
        return backupTasks;
    }

    public void stopBackup() {
        if (ffmpegProcess != null && ffmpegProcess.isAlive()) {
            ffmpegProcess.destroy();
            System.out.println("备份任务已停止");
            backupTasks.put("status", "stopped");
            isBackupRunning = false;
        }
    }
}